package com.jian.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TimeUtils
{

	private TimeUtils() {
	}

	private static String gettimecommon(SimpleDateFormat sdf, long time)
	{
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		return sdf.format(time);

	}



	/**
	 * 将字符串转位日期类型
	 * 
	 * @param sdate
	 * @return
	 */
	public static Date toDate(String sdate)
	{
		try {
			return dateFormater.get().parse(sdate);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 判断给定字符串时间是否为今日
	 * 
	 * @param sdate
	 * @return boolean
	 */
	public static boolean isToday(String sdate)
	{
		boolean b = false;
		Date time = toDate(sdate);
		Date today = new Date();
		if (time != null) {
			String nowDate = dateFormater2.get().format(today);
			String timeDate = dateFormater2.get().format(time);
			if (nowDate.equals(timeDate)) {
				b = true;
			}
		}
		return b;
	}

	private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue()
		{
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
	};

	private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue()
		{
			return new SimpleDateFormat("yyyy-MM-dd");
		}
	};

	

	/**
	 * 获取时间 格式:MM-dd HH:mm
	 * 
	 * @param time
	 * @return
	 */
	public static String getMMddHHmm(long time)
	{
		SimpleDateFormat df = new SimpleDateFormat("MM-dd" + TIMEKONGGE
				+ "HH:mm");
		return gettimecommon(df, time);
	}

	private static final String TIMEKONGGE = "  ";

	/**
	 * 获取时间 格式 yyyy-MM-dd HH:mm
	 * 
	 * @param time
	 * @return
	 */
	public static String gettime(long time)
	{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd" + TIMEKONGGE
				+ "HH:mm");
		return gettimecommon(df, time);
	}

	/**
	 * 获取时间 将时间字符串转换成long ，根据格式转换
	 * 
	 * @param time
	 * @return
	 */
	public static Long getTimeLong(String time)
	{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd" + TIMEKONGGE
				+ "HH:mm");
		df.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		Date dt = null;
		try {
			dt = df.parse(time);
			return dt.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return (long) 0;
	}

	private static final SimpleDateFormat sdfall = new SimpleDateFormat(
			"yyyy-MM-dd" + TIMEKONGGE + "HH:mm:ss");

	public static String timeFormat(long time)
	{
		return gettimecommon(sdfall, time);

	}

	public static String timeFormatNoss(long time)
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd" + TIMEKONGGE
				+ "HH:mm");
		return gettimecommon(sdf, time);

	}
}
